package com.yisu.expressway.manager.domain.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 对外接口签名算法
 * Created by xlt on 2017/4/19.
 */
public class SignatureAlgorithm {
    private static String SECRET_KEY = "lubobo";

    /**
     * 签名验证
     *
     * @param param 参数
     * @param sign  待验证签名值
     * @return
     */
    public boolean signVerify(Map<String, String> param, String sign) {
        return getSign(param).equals(sign);
    }

    /**
     * 获取参数签名
     *
     * @param param
     * @return
     */
    public String getSign(Map<String, String> param) {
        String sign = "";
        try {
            String paramContent = SECRET_KEY;
            //对参数进行排序后进行签名
            param = sortMapByKey(param);
            for (Iterator it = param.keySet().iterator(); it.hasNext(); ) {
                String key = (String) it.next();
                paramContent += key + "";
                paramContent += param.get(key);
            }
            sign = EncoderByMd5(paramContent).toUpperCase();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return sign;
    }

    public String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(str.getBytes());
        //加密后的字符串
        String newstr =  new BigInteger(1, md5.digest()).toString(16);
        return newstr;
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }


}

class MapKeyComparator implements Comparator<String> {
    public int compare(String str1, String str2) {
        return str1.toLowerCase().compareTo(str2.toLowerCase());
    }
}
